<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/2/3
 * Use : ...
 * File: MemcacheSessionHandler.php
 */

namespace ulue\parts\session\handler;


class MemcacheSessionHandler extends AbstractSessionHandler
{
    protected $memcache=null;

    /**
     * Property ttl. 存储周期
     * @var  integer
     */
    protected $ttl = null;

    public function __construct(\Memcache $memcache=null, $options=[])
    {
        if (!self::isSupported())
        {
            throw new \DRuntimeException('Memcached Extension is not available');
        }

        $this->memcache = $memcache instanceof \Memcache ? $memcache : new \Memcache();

        $this->ttl = isset($options['expire']) ? $options['expire'] : 2*60*60;

        parent::__construct($options);
    }


    static public function isSupported()
    {
        return (extension_loaded('memcache') && class_exists('Memcache'));
    }

    public function open($path, $name)
    {
        return true;
    }

    public function read( $id )
    {
        return $this->memcache->get($this->prefix.$id) ?: '';
    }

    public function write( $id ,  $data )
    {
        return $this->memcache->set($this->prefix.$id, $data, 0, time() + $this->ttl);
    }

    public function destroy( $id )
    {
        return  $this->memcache->delete($this->prefix.$id);
    }

    public function gc( $maxlifetime )
    {
        return  true ;
    }

    public function close()
    {
        $this->memcache->close();

        return true;
    }

    public function getMemcache()
    {
        return $this->memcache;
    }

    public function setMemcache($mem)
    {
        return $this->memcache = $mem;
    }

}// end class MemcacheSessionHandler